package org.prail.net.core;

import java.io.BufferedOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.prail.threads.DownloadThread;
import org.prail.wrappers.SearchResult;

public class Download {

	public Download(final DownloadThread t, final SearchResult result) {
		try {
			URL url = new URL(result.getMP3Url());
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			int filesize = connection.getContentLength();
			float totalDataRead = 0;
			java.io.BufferedInputStream in = new java.io.BufferedInputStream(
					connection.getInputStream());
			java.io.FileOutputStream fos = new java.io.FileOutputStream(result.getSaveFile());
			java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,
					1024);
			byte[] data = new byte[1024];
			int i = 0;
			while ((i = in.read(data, 0, 1024)) >= 0) {
				totalDataRead = totalDataRead + i;
				bout.write(data, 0, i);
				float Percent = (totalDataRead * 100) / filesize;
				t.setValue((int) Percent);
			}
			bout.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
